﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;

namespace RemindMe
{
    public partial class SettingsForm : Form
    {
        ApplicationSettingsBase settings;

        public SettingsForm(ApplicationSettingsBase settings)
        {
            InitializeComponent();

            this.settings = settings;
            foreach (SettingsProperty setting in settings.Properties)
            {
                if(setting.PropertyType == typeof(String)){
                    Label settingLabel = new Label();
                    settingLabel.Text = setting.Name;
                    TextBox settingTxt = new TextBox();
                    settingTxt.Enabled = !setting.IsReadOnly;
                    settingTxt.Dock = DockStyle.Fill;
                    SettingsPropertyValue propertyValue = settings.PropertyValues[setting.Name];
                    string value = (string)settings.GetType().GetProperty(setting.Name).GetValue(settings, null);
                    settingTxt.Text = value;
                    this.tableLayoutPanel1.Controls.Add(settingLabel);
                    this.tableLayoutPanel1.Controls.Add(settingTxt);
                }
            }
        }

        private void applySettings()
        {
            System.Collections.IEnumerator controlEnumerator = this.tableLayoutPanel1.Controls.GetEnumerator();
            while (controlEnumerator.MoveNext())
            {
                string settingName = (controlEnumerator.Current as Control).Text;
                if (controlEnumerator.MoveNext())
                {
                    string settingValue = (controlEnumerator.Current as Control).Text;
                    settings.GetType().GetProperty(settingName).SetValue(settings, settingValue, null);
                }
            }
        }

        private void btnApply_Click(object sender, EventArgs e)
        {
            applySettings();
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            applySettings();
            this.settings.Save();
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }
    }
}
